package cn.virens.server.tio_tcp;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.DefaultAioListener;
import org.tio.core.intf.Packet;

import cn.virens.common.exception.ReconnectException;
import cn.virens.common.exception.TimeoutException;
import cn.virens.server.tio_tcp.handler.PacketHandler;

public class TIOServerListener extends DefaultAioListener {
	private static final Logger logger = LoggerFactory.getLogger(TIOServerListener.class);

	public TIOServerListener(List<PacketHandler> handlerMap) {
	}

	@Override
	public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) {
		logger.debug("已连接({})-成功:{}-重连:{}", TIOServerUtil.name(channelContext), isConnected, isReconnect);
	}

	@Override
	public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
		logger.debug("总接收({})-长度:{} bytes", TIOServerUtil.name(channelContext), receivedBytes);
	}

	@Override
	public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) {
		logger.debug("已接收({})-长度:{} bytes", TIOServerUtil.name(channelContext), packetSize);
	}

	@Override
	public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
		logger.debug("已发送({})-成功:{}", TIOServerUtil.name(channelContext), isSentSuccess);
	}

	@Override
	public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
		logger.debug("已处理({})-耗时:{} ms", TIOServerUtil.name(channelContext), cost);
	}

	@Override
	public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
		if (throwable instanceof ReconnectException) {
			logger.debug("已断开({})-重连:{}-{}", TIOServerUtil.name(channelContext), str(remark), str(throwable));
		} else if (throwable instanceof TimeoutException) {
			logger.debug("已断开({})-超时:{}-{}", TIOServerUtil.name(channelContext), str(remark), str(throwable));
		} else {
			logger.debug("已断开({})-异常:{}-{}", TIOServerUtil.name(channelContext), str(remark), str(throwable));
		}

		// 释放连接信-绑定信息
		TIOServerUtil.unbindToken(channelContext);
		TIOServerUtil.unbindImsi(channelContext);
	}

	private static String str(Object obj) {
		return obj == null ? "" : obj.toString();
	}
}
